package com.rslai.commons.validator.jsonvalidator.validators;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rslai.commons.validator.jsonvalidator.exception.UnSupportedTypeException;
import com.rslai.commons.validator.jsonvalidator.matchers.JsonAssert;
import org.hamcrest.Matchers;
import org.junit.Assert;

import java.util.List;

/**
 * JSON校验器，数组或List大小校验器
 */
public class SizeValidator extends Validator {
    public static final String VALIDATOR_NAME = "size";
    int size;

    /**
     * 构造函数
     * @param argument object list
     */
    public SizeValidator(List<Object> argument) {
        size = Integer.valueOf(argument.get(0).toString());
    }

    /**
     * 校验JSON对象
     * @param object 待验证的JSON对象
     */
    @Override
    public void doValidate(Object object) {
        if (object == null) {
            JsonAssert.fail("size不能校验为null的值", "必须传入值", object);
        }
        if (object instanceof JSONObject) {
            Assert.assertThat(((JSONObject) object).keySet().size(), Matchers.is(size));
        } else if (object instanceof JSONArray) {
            Assert.assertThat(getCurrentKeyPath() + " size not equals", ((JSONArray) object).size(), Matchers.is(size));
        } else {
            throw new UnSupportedTypeException(String.format("size validator unsupported type <%s>", object.getClass()));
        }
    }

    /**
     * 返回校验名称
     * @return 校验名称
     */
    @Override
    public String name() {
        return VALIDATOR_NAME;
    }

}
